$package('itsm.portal');

$import('common.security.organizationTreeUtil');
$import("common.config.category.eventCategoryTree");
$import("common.security.userUtil");
if(isCIHave){
	$import("itsm.cim.configureItemUtil");
}

$import("common.config.dictionary.dataDictionaryUtil");
$import('itsm.itsop.selectCompany');
$import('common.config.includes.includes');
/**  
 * @fileOverview "语音卡主函数"
 * @author QXY  
 * @constructor Tan
 * @description 语音卡主函数
 * @date 2011-12-13
 * @version 1.0  
 * @since version 1.0 
 */
itsm.portal.voiceCard= function() {
	this._callShowLoginName='Null';
	this._callShowFullName='Null';
	this._callShowuserId='Null';
	var operator;
	return {
		
		/**
		 * @description tab点击事件
		 */
		tabClick:function(){
            $('#callShowTab').tabs({
                onSelect:itsm.portal.voiceCard.tabClickEvents
            });
		},
		tabClickEvents:function(title){
			if(title==i18n['title_relatedRequest']){
				itsm.portal.voiceCard.callShowRelatedRequestGrid();
			}
			if(title==i18n['relatedCI']){
				itsm.portal.voiceCard.callShowCiGrid();
			}
		},
		/**
		 * @description 关联请求列表
		 */
		callShowRelatedRequestGrid:function(){
			if($("#callShowRelatedRequestGrid").html()==''){
				var params=$.extend({},jqGridParams,{
					url:'request!findRequests.action?requestQueryDTO.createdByName='+_callShowLoginName+'&requestQueryDTO.currentUser='+userName+'&requestQueryDTO.lastUpdater='+userName,
					colNames:['',i18n['common_id'],i18n['common_title'],i18n['common_state'],i18n['common_createTime']],
					colModel:[
					          {name:'eno',hidden:true},
							  {name:'requestCode',width:85,sortable:false},
							  {name:'etitle',align:'center',width:110,sortable:false},
							  {name:'statusName',width:70,align:'center',sortable:false},
							  {name:'createdOn',width:95,align:'center',formatter:timeFormatter,sortable:false}
							  ],
					jsonReader: $.extend(jqGridJsonReader, {id: "eno"}),
					sortname:'eno',
					pager:'#callShowRelatedRequestPager',
					ondblClickRow:function(rowId){itsm.portal.voiceCard.showRequestDeatils(rowId)},
					autowidth:true,
					toolbar:false,
					multiselect:false
				});
				$("#callShowRelatedRequestGrid").jqGrid(params);
				$("#callShowRelatedRequestGrid").navGrid('#callShowRelatedRequestPager',navGridParams);
				setGridWidth("#callShowRelatedRequestGrid","callShowCenter",8);
			}else{
			    if (_callShowuserId == 'Null') {
                    $('#callShowRelatedRequestGrid').jqGrid('clearGridData');
                } else {
                    $('#callShowRelatedRequestGrid').jqGrid('setGridParam',{page:1,url:'request!findRequests.action?requestQueryDTO.createdByName='+_callShowLoginName+'&requestQueryDTO.currentUser='+userName+'&requestQueryDTO.lastUpdater='+userName}).trigger('reloadGrid');
                }
			}
		},
		showRequestDeatils:function(eno){
			basics.tab.tabUtils.reOpenTab("request!requestDetails.action?eno="+eno,i18n["request_detail"]);
		},
		/**
		 * @description 配置項列表.
		 */
		callShowCiGrid:function(){
			if($('#callShowRelatedCiGrid').html()!=''){
			    if (_callShowuserId == 'Null') {
			        $('#callShowRelatedCiGrid').jqGrid('clearGridData');
	            } else {
	                var ci_url ='ci!findPageConfigureItemByUser.action';
	                $('#callShowRelatedCiGrid').jqGrid('setGridParam',{page:1,url:ci_url}).trigger('reloadGrid');
	            }
			}else{
				var params = $.extend({},jqGridParams,{
					url:'ci!findPageConfigureItemByUser.action',
					postData:{'ciQueryDTO.loginName':_callShowFullName},
					colNames:['',i18n['category'],i18n['number'],i18n['name'],i18n['status']],
					colModel:[
					          {name:'ciId',hidden:true},
							  {name:'categoryName',align:'center',width:20,sortable:false},
							  {name:'cino',align:'center',width:30},
							  {name:'ciname',align:'center',width:30},
							  {name:'status',align:'center',width:10,sortable:false}
							  ],
					toolbar:false,
					jsonReader: $.extend(jqGridJsonReader,{id: "ciId"}),
					sortname:'ciId',
					multiselect:false,
					pager:'#callShowRelatedCiPager',
					ondblClickRow:function(rowId){
						itsm.portal.voiceCard.configureItemInfo(rowId);
					}
				});
				$('#callShowRelatedCiGrid').jqGrid(params);
				$('#callShowRelatedCiGrid').navGrid('#callShowRelatedCiPager',navGridParams);
				setGridWidth("#callShowRelatedCiGrid","callShowCenter",8);
				
			}	
		},
		/**@description 打开详细信息页面*/
		configureItemInfo:function(ciId){
			basics.tab.tabUtils.reOpenTab('ci!findByciId.action?ciEditId='+ciId,i18n['ci_configureItemInfo']);
		},
		
		//截取字符串,str:原字符，s：要截取的内容
		interceptStr:function(str,s){
			var ph='';
			if(str!=null){
				var str1=str.split(',');
				for(var i=0;i<str1.length;i++){
					if(str1[i].indexOf(s)>=0){
						ph=str1[i].substr(str1[i].indexOf('=')+1);
						return ph;
					}
				}
			}else{
				return ph;
			}
		},
		
		//打开来电显示窗口
		openCallWindow:function(req){
		    
		    // 清空历史
		    _callShowuserId = 'Null';
		    
			//号百软坐席
			if(req.indexOf('callNumber=')!=-1){
				itsm.portal.voiceCard.haoBaiAgentDesk(req);
			}else{
				/*语音卡*/
				$('#callShow_create_requet_link').unbind();
				$('#callShow_create_requet_link').click(function(){
					if(_callShowuserId!='Null'){
						basics.tab.tabUtils.refreshTab(i18n["title_request_addRequest"],'../pages/itsm/request/addRequestFormCustom.jsp?phoneNum='+$('#callNumber').val()+'&voiceCarduserId='+_callShowuserId);
						$('#call_window').dialog('close');
					}else{
						msgAlert(i18n['msg_request_vaildateRequester'],'info');
					}
				});
				$('#callShow_create_user_link').unbind();
				$('#callShow_create_user_link').click(itsm.portal.voiceCard.callShowCreateUser);
				
				var _ph=itsm.portal.voiceCard.interceptStr(req,'ph=');
				$('#callNum').text(_ph);
				$('#callNumber').val(_ph);
				itsm.portal.voiceCard.findUserByNumber(_ph);
				windows('call_window',{width:720,height:480,modal: false});
				itsm.portal.voiceCard.tabClick();
				$('#callShowTab').tabs();
				$.parser.parse($('#call_window'));
			}
			
		},
		findUserByNumber:function(_ph){
			$.post('user!findUserByNumber.action','userQueryDto.mobilePhone='+_ph,function(res){
				$('#customInfo table tbody').empty();
				if(res!=null && res.data && res.data.length>0){
					var _tr="<tr  onclick='itsm.portal.voiceCard.loadUserInfo({id})' id='customInfo_tr_{trId}'><td align='left'>{userId}</td><td><a>{loginName}</a></td><td>{fullName}</td></tr>";
					var defaultLoadId=0;
					for(var i=0;i<res.data.length;i++){
						if(defaultLoadId==0){//加载默认项
							defaultLoadId=res.data[i].userId;
							setTimeout(function(){
								itsm.portal.voiceCard.loadUserInfo(defaultLoadId);
							},500);
						}
						$('#customInfo table tbody').append(_tr.replace('{userId}',res.data[i].userId).replace('{loginName}',res.data[i].loginName).replace('{id}',res.data[i].userId).replace('{trId}',res.data[i].userId).replace('{fullName}',res.data[i].fullName));
					}
					$('#callShow_create_user_div').removeClass('hisdiv');
					$('#callShow_create_user_div').addClass('content');
				}else{
					$('#customInfo table tbody').append('<tr><td colspan="3" style="color:#FF0000;font-size:16px">'+i18n['noData']+'</td></tr>');
					$('#callShowTab table span').text('');
					$('#callShow_create_user_div').removeClass('content');
					$('#callShow_create_user_div').addClass('hisdiv');
				}
			});
		},
		userSetInput:function(value){
			if(value!=null)
				return value;
			else
				return "";
		},
		//创建请求
		callShowCreateRequest:function(){
			if(_callShowLoginName!='Null')
			$('#callShow_selectCreator').val(_callShowLoginName);
			
			$('#callShow_save_request_link,#callShow_selectCreator,#callShow_ciname,#callShow_request_categoryName').unbind();
			//选择公司
			$('#callShow_request_companyName').click(function(){
				itsm.itsop.selectCompany.openSelectCompanyWin('#callShow_request_companyNo','#callShow_request_companyName','#callShow_ciname,#callShow_ciid,#callShow_selectCreator,#callShow_addRequestUserId');
			});
			//加载默认公司
			common.security.defaultCompany.loadDefaultCompany('#callShow_request_companyNo','#callShow_request_companyName');
			$('#callShow_ciname').click(function(){
				itsm.cim.configureItemUtil.findConfigureItemByLoginName('#callShow_ciname','#callShow_ciid',$('#callShow_selectCreator').val());
			});	
			
			$('#callShow_request_categoryName').click(function(){
				common.config.category.eventCategoryTree.showSelectTree('#request_category_select_window'
						,'#request_category_select_tree'
						,'Request'
						,'#callShow_request_categoryName'
						,'#callShow_request_categoryNo');
				
			});
			
			$('#callShow_save_request_link').click(itsm.portal.voiceCard.saveRequest);
			$('#callShow_selectCreator').click(itsm.portal.voiceCard.selectRequestCreator);
			//加载数据字典
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('effectRange','#callShow_request_effectRange');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('seriousness','#callShow_request_seriousness');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('imode','#callShow_request_imode');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('level','#callShow_request_level');
			common.config.dictionary.dataDictionaryUtil.loadOptionsByCode('priority','#callShow_request_priority');
			windows('callShow_create_request_window',{width:580});
		},
		//打开新建用户窗口
		callShowCreateUser:function(){
			$('#loginName').removeAttr("readonly");
			resetForm('#callShow_addUserForm');
			$('#callShow_userOtherInfo input').val('');
			$('#callShow_user_companyNo').val(companyNo);
			var phoneNum = $('#callNumber').val();
			if(phoneNum.length < 11||phoneNum.indexOf('-')!=-1){  //电话
				$('#callShow_user_phone').val(phoneNum);
			}else{
				$('#callShow_user_moblie').val(phoneNum);
			}
			$('#callShow_user_roleCode').val('ROLE_ENDUSER');
			$('#callShow_user_orgName').unbind();
			$('#callShow_user_orgName').click(function(){
				common.security.organizationTreeUtil.showAll_2('#callShow_addUserForm_userGroup_win','#callShow_userGroupTree','#callShow_user_orgName','#callShow_user_orgNo',companyNo);
			});
			$('#callShow_link_user_save').unbind();
			$('#callShow_link_user_save').click(function(){
				itsm.portal.voiceCard.saveUser();
			});
			var randnum = Math.floor(Math.random()*1000000);
			$('#callShow_user_loginName').val(randnum);
			$('#callShow_user_password').val(randnum);
			$('#callShow_user_rpassword').val(randnum);
			windows('callShow_create_user_window',{width:650,modal: false});
			operator = 'save';
			$.parser.parse($('#callShow_create_user_window'));
		},
		//保存用户
		saveUser:function(){
			$.post('user!userExist.action','userDto.loginName='+$("#callShow_user_loginName").val(),function(data){
				if(data){
					if($('#callShow_addUserForm').form('validate')){
						var param = $('#callShow_addUserForm,#callShow_userOtherInfo_form').serialize();
						var url = "user!save.action";
						$.post(url,param,function(){
							$('#callShow_create_user_window').dialog('close');
							//刷新原有数据
							var num=$('#callNumber').val();
							itsm.portal.voiceCard.findUserByNumber(num);
							itsm.portal.voiceCard.tabClick();
							$('#callShowTab').tabs();
						});
					}
				}else{
					msgAlert(i18n['error_userExist'],'info');
				}
			});
		},
		/**
		 * @description 提交保存请求.
		 */
		saveRequest:function(){
			if($('#callShow_create_request_form').form('validate')){
				var frm = $('#callShow_create_request_form').getForm();
				var url = 'request!saveRequest.action';
				//调用
				startProcess();
				$.post(url,frm, function(eno){
					msgShow(i18n['msg_request_addSuccessful'],'show');
					endProcess();
					basics.tab.tabUtils.closeTab(i18n['title_request_addRequest']);
					showRequestIndex();
					basics.tab.tabUtils.reOpenTab("request!requestDetails.action?eno="+eno,i18n["request_detail"]);
					$('#requestGrid').trigger('reloadGrid');
					//清空上一次的值
					$('#callShow_create_request_window input').val('');
					$('#callShow_request_edesc').val('');
					$('#callShow_create_request_window').dialog('close');
				});
				
			}
		},
		/**
		 * 选择请求者.
		 */
		selectRequestCreator:function(){
			common.security.userUtil.selectUser('#callShow_selectCreator','#callShow_addRequestUserId','','loginName',$('#callShow_request_companyNo').val());
		},
		//加载当前用户详细信息
		loadUserInfo:function(id){
			_callShowuserId=id;
			$("#customInfoTable td").css({"background":"#fff"});//全部修改为白色
			$("#customInfo_tr_"+id+" td").css({"background":"#ffef8f"});//修改为选定
			$.post('user!findUserDetail.action','userDto.userId='+id,function(data){
				_callShowLoginName=data.loginName;
				_callShowFullName=data.fullName;
				$('#callShow_userLastName').text(itsm.portal.voiceCard.userSetInput(data.firstName));
				$('#callShow_userFirstName').text(itsm.portal.voiceCard.userSetInput(data.lastName));
				$('#callShow_userOwnerOrg').text(itsm.portal.voiceCard.userSetInput(data.orgName));
				$('#callShow_userTitle').text(itsm.portal.voiceCard.userSetInput(data.firstName));
				$('#callShow_position').text(itsm.portal.voiceCard.userSetInput(data.position));
				if(data.userState==false){
					$('#callShow_userState').text(i18n['disable']);
				}else
				{
					$('#callShow_userState').text(i18n['enable']);
				}
				if(data.sex==true){
					$('#callShow_sex').text(i18n['label_user_man']);
				}else
				{
					$('#callShow_sex').text(i18n['label_user_woman']);
				}
				$('#callShow_icCard').text(itsm.portal.voiceCard.userSetInput(data.icCard));
				$('#callShow_pinyin').text(itsm.portal.voiceCard.userSetInput(data.pinyin));
				$('#callShow_birthday').text(itsm.portal.voiceCard.userSetInput(data.birthday));
				$('#callShow_email').text(itsm.portal.voiceCard.userSetInput(data.email));
				$('#callShow_mobile').text(itsm.portal.voiceCard.userSetInput(data.moblie));
				$('#callShow_phone').text(itsm.portal.voiceCard.userSetInput(data.phone));
				$('#callShow_fax').text(itsm.portal.voiceCard.userSetInput(data.fax));
				$('#callShow_qqOrMsn').text(itsm.portal.voiceCard.userSetInput(data.msn));
				$('#callShow_workAddress').text(itsm.portal.voiceCard.userSetInput(data.officeAddress));
				$('#callShow_description').text(itsm.portal.voiceCard.userSetInput(data.description));
				
				if($("#callShowRelatedRequestGrid").html()!=''){
					$('#callShowRelatedRequestGrid').jqGrid('setGridParam',{page:1,url:'request!findRequests.action?requestQueryDTO.createdByName='+_callShowLoginName+'&requestQueryDTO.currentUser='+userName+'&requestQueryDTO.lastUpdater='+userName}).trigger('reloadGrid');
				}
				if($("#callShowRelatedCiGrid").html()!=''){
					$('#callShowRelatedCiGrid').jqGrid('setGridParam',{page:1,url:'ci!findPageConfigureItemByUser.action',postData:{'ciQueryDTO.loginName':_callShowFullName}}).trigger('reloadGrid');
				}
				
				
			})
		},
		
		chStatus:function(url,param){
			if(url !==null && url !== ''){
				$.post(url,param,function(xml){
					if(xml!=null){
						var json = $.xml2json(xml);
						setTimeout(function(){
							var data=json.chStatus;
							if(data!=null && data!=undefined && data!=''){
								$.each(data,function(i,item){
									var _str='<tr>'+
									'<td>{ch}</td>'+
									'<td>{type}</td>'+
									'<td>{status}</td>'+
									'<td>{step}</td>'+
									'<td>{phone}</td>'+
									'<td>{oper}</td>'+
									'<td>{startTime}</td>'+
									'<td>{remoteIP}</td>'+
									'</tr>';
									_str=_str.replace('{ch}',item.ch)
									.replace('{type}',item.type)
									.replace('{status}',item.status)
									.replace('{step}',item.step)
									.replace('{phone}',item.phone)
									.replace('{oper}',item.oper)
									.replace('{startTime}',item.startTime)
									.replace('{remoteIP}',item.remoteIP)
									.replace(/_NA_/g,'');
									$('#chunnelStatus tbody').append(_str);
								});
							}else{
								$('#chunnelStatus tbody').html('');
								$('#chunnelStatus tbody').append('<tr><td align="center" colspan="11" style="color:red;font-size:16px">'+i18n['noData']+'</td></tr>');
							}
						},1500);
					};
				});
			}else{
				msgAlert(i18n['label_call_set_voiceCard'],'info');
			}
		},
		
		callShowTest:function(){
			var _number=$('#callNumber').val();
			if(_number!=null && _number!=''){
				var pck  =/^((\+?[0-9]{2,4}\-[0-9]{3,4}\-)|([0-9]{3,4}\-))?([0-9]{5,8})(\-[0-9]+)?$/;
				var mck = /^1[3,5,8,9]\d{9}$/;
				if(pck.test(_number) || mck.test(_number))
					itsm.portal.voiceCard.openCallWindow('ph='+_number);
				else
					msgAlert(i18n['validate_phone_number'],'info');
			}else{
				msgAlert(i18n['validate_notNull'],'info');
			}
		},
		//号百软坐席呼叫中心集成
		haoBaiAgentDesk:function(req){
			var _callNumber = '';
			var _keyLoggers = '';
			var _req = req.split('&');
			$.each(_req,function(k,v){
				if(v.indexOf('callNumber=')!=-1){
					_callNumber = v.split('=')[1];
				}
				if(v.indexOf('keyLoggers=')!=-1){
					_keyLoggers = v.split('=')[1];
				}
				if(k+1==_req.length){
					common.config.includes.includes.loadCategoryIncludesFile();
					basics.tab.tabUtils.refreshTab(i18n["title_request_addRequest"],'../pages/itsm/request/addRequest.jsp?callNumber='+_callNumber+'&keyLoggers='+_keyLoggers);
				}
			});
			
		},
		
		init:function(){
			basics.includes.loadVoiceCardIncludesFile();
		}
	}
}();
$(function(){itsm.portal.voiceCard.init});